<template>
  <view class="wrap">
    <image
      src="../../static/me-bg.png"
      mode="aspectFill"
      style="width: 100vw; height: 60vw; position: absolute; left: 0; top: -88rpx; z-index: -1;"
    />
    <view style="position: fixed; top: 0; left: 0; width: 100vw;">
      <view class="typeWrap">
        <view @click="changeType(1)" :class="type === 1 ? 'typeItem typeItemActive': 'typeItem'">我的直推</view>
        <view @click="changeType(2)" :class="type === 2 ? 'typeItem typeItemActive': 'typeItem'">我的间推</view>
      </view>
      <view class="timeWrap">
        <view class="time" @click="showTimePick = true">
          {{`${yearTime}年${monthTime ? `${monthTime}月`:''}`}}
          <u-icon name="arrow-down" color="#fff" :size="24"></u-icon>
        </view>
        <view class="useWrap">
          <view @click="isUse = true" :class="isUse ? 'useItem useItemActive' : 'useItem'">使用</view>
          <view @click="isUse = false" :class="isUse ? 'useItem' : 'useItem useItemActive'" style="margin-left: 32rpx;">充值</view>
        </view>
      </view>
      <view style="padding:0 24rpx; color: #fff;margin-top: 32rpx;">
        <view style="margin-bottom: 24rpx;">合计：</view>
        <view class="totalPointWrap">
          <view>积分：{{ isUse ? totalUsedPoint : totalRechargePoint }}</view>
          <view style="margin-left: 24rpx;">其他积分：{{ isUse ? totalUsedRealPoint : totalRechargeRealPoint }}</view>
        </view>
      </view>
    </view>
    <view style="width: 100vw; height: calc(100vh - 60vw + 88rpx); margin-top: calc(60vw - 88rpx);">
      <scroll-view scroll-y="true" class="list" :refresher-enabled="enabled" :refresher-triggered="triggered" @scroll-top=""
        :refresher-threshold="100" :lower-threshold="200" refresher-background="#F8F8F8" @refresherrefresh="onRefresh"
        @refresherrestore="onRestore" @scrolltolower="scrolltolower">
        <template v-if="modelList?.length">
          <view v-for="item in modelList" class="modelItem">
            <view style="margin-right: 24rpx;">
              <u-avatar :src="item.headUrl" size="88"></u-avatar>
            </view>
            <view class="modelRightItem">
              <view style="max-width: 60%; flex-shrink: 0;">
                <up-text type="" size="36" color="#000" :text="item.nickName" :lines="1" margin="0 0 16rpx"></up-text>
                <up-text type="" size="28" color="#666" :text="`邀请人：${item.inviteUserName}`" :lines="1"></up-text>
              </view>
              <view style="flex-shrink: 0; margin-left: 24rpx;">
                <up-text type="" size="28" color="#000" :text="`积分：${ isUse ? item.usedPoint : item.rechargePoint }`" :lines="1" margin="0 0 16rpx"></up-text>
                <up-text type="" size="28" color="#000" :text="`其他积分：${ isUse ? item.usedRealPoint : item.rechargeRealPoint }`" :lines="1"></up-text>
              </view>
            </view>
          </view>
          <view style="height: 32rpx; width: 100%;"></view>
          <up-loadmore :status="status" fontSize="28" iconSize="34" />
          <view style="height: 80rpx; width: 100%;"></view>
        </template>
        <template v-else class="row emptyWrap">
          <common-empty />
        </template>
      </scroll-view>
    </view>
    <u-picker :show="showTimePick" ref="uPicker" :columns="columns" itemHeight="88"
    @confirm="confirm" @change="changeHandler" @cancel="showTimePick = false" keyName="label"></u-picker>
  </view>
</template>

<script>
import dayjs from 'dayjs';
import { queryMyPerformance } from '@/services/performance';

export default {
  data() {
    return {
      type: 1,
      isUse: true,
      page: 1,
      startTimeStamp: '',
      endTimeStamp: '',
      loading: true,
      totalUsedPoint: 0,
      totalUsedRealPoint: 0,
      totalRechargePoint: 0,
      totalRechargeRealPoint: 0,
      modelList: [],
      total: 0,
      showTimePick: false,
      columns: [],

      enabled: true,
      triggered: 'restore',
    }
  },
  computed: {
    yearTime() {
      const year = dayjs(this.startTimeStamp).year();
      return year;
    },
    monthTime() {
      const month = dayjs(this.startTimeStamp).month();
      const endMoth = dayjs(this.endTimeStamp).month();
      if (month === endMoth) {
        return month + 1;
      }
      return null;
    },
    status() {
      if (this.loading || this.total > this.page * 10) {
        return 'loading'
      }
      return 'nomore'
    },
  },
  onLoad(option) {
    this.startTimeStamp = dayjs().startOf('month').valueOf();
    this.endTimeStamp = dayjs().endOf('month').valueOf();
    const year = dayjs().year();
    const month = dayjs().month() + 1;
    this.columns = [
      Array(10).fill('').map((item, idx) => ({
        label: `${year - 9 + idx}年`,
        value: year - 9 + idx
      })),
      Array(month).fill('').map((item, idx) => ({
        label: `${idx + 1}月`,
        value: idx + 1
      })).concat({
        label: '全年',
        value: 0
      }),
    ]
    console.log(this.columns, year, month, this.startTimeStamp);
    const picker = this.$refs.uPicker;
    picker.setIndexs([9, month - 1], true);
    this.getData();
  },
  onReady() {
  },
  onShow() {
  },
  methods: {
    changeType(type) {
      this.type = type;
      this.getData();
    },
    confirm({ value }) {
      const [yearItem, monthItem] = value || [];
      if (monthItem.value === 0) {
        this.startTimeStamp = dayjs(`${yearItem.value}-01`, 'YYYY-MM').startOf('month').valueOf();
        this.endTimeStamp = dayjs(`${yearItem.value}-12`, 'YYYY-MM').endOf('month').valueOf();
      } else {
        this.startTimeStamp = dayjs(`${yearItem.value}-${monthItem.value}`, 'YYYY-MM').startOf('month').valueOf();
        this.endTimeStamp = dayjs(`${yearItem.value}-${monthItem.value}`, 'YYYY-MM').endOf('month').valueOf();
      }
      this.showTimePick = false;
      this.page = 1;
      this.getData();
    },
    changeHandler(e) {
      const {
        columnIndex,
        index,
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs.uPicker
      } = e;
      if (columnIndex === 0) {
        let monthList = Array(12).fill('').map((item, idx) => ({
          label: `${idx + 1}月`,
          value: idx + 1
        })).concat({
          label: '全年',
          value: 0
        });
        if (index === 9) {
          const month = dayjs().month() + 1;
          monthList = Array(month).fill('').map((item, idx) => ({
            label: `${idx + 1}月`,
            value: idx + 1
          })).concat({
            label: '全年',
            value: 0
          })
        };
        picker.setColumnValues(1, monthList)
      }
    },
    async onRefresh() {
      if (this.loading) return;
      const _that = this;
      this.page = 1;
      await this.getData();
      _that.triggered = false;
    },
    onRestore() {
      this.triggered = 'restore'; // 需要重置
    },
    scrolltolower() {
      console.log('scrolltolower')
      if (!this.loading && this.total > this.page * 10) {
        console.log('获取更多');
        this.page = this.page + 1;
        this.getData();
      }
    },
    async getData() {
      const { type, page, startTimeStamp, endTimeStamp } = this;
      this.loading = true;
      const _that = this;
      const params = {
        startTimeStamp,
        endTimeStamp,
        page,
        type,
        limit:10
      };
      const res = await queryMyPerformance(params);
      if (res?.success) {
        const { totalUsedPoint, totalUsedRealPoint, totalRechargePoint, totalRechargeRealPoint, total, modelList } = res.data || {};
        _that.totalUsedPoint = totalUsedPoint || 0;
        _that.totalUsedRealPoint = totalUsedRealPoint || 0;
        _that.totalRechargePoint = totalRechargePoint || 0;
        _that.totalRechargeRealPoint = totalRechargeRealPoint || 0;
        _that.total = total || 0;
        let list = [...(modelList || [])];
        if (page === 1) {
          _that.modelList = list;
        } else {
          _that.modelList = _that.modelList.concat(list);
        }
      }
      this.loading = false;
    },
  },
}
</script>

<style lang="scss" scoped>
.wrap {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
}

.typeWrap {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 50vw;
  margin: 24rpx auto;
}

.typeItem {
  font-size: 32rpx;
  color: #fff;
  opacity: 0.6;
}

.typeItemActive {
  opacity: 1;
  border-bottom: 4rpx solid #fff;
}

.timeWrap {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: calc(100vw - 48rpx);
  padding: 0 24rpx 24rpx;
}

.time {
  font-size: 32rpx;
  color: #fff;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.useWrap {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.useItem {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4rpx 8rpx;
  font-size: 28rpx;
  color: #fff;
  opacity: 0.6;
}

.useItemActive {
  opacity: 1;
  border: 1rpx solid #fff;
  border-radius: 12rpx;
}

.totalPointWrap {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  font-size: 42rpx;
}

.emptyWrap {
  height: 100%;
  width: 100%;
  flex: 1;
  justify-content: center;
}
.list {
  width: 100vw;
  height: calc(100vh - 60vw + 88rpx);
}

.modelItem {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 0 24rpx;
  width: calc(100vw - 48rpx);
}

.modelRightItem {
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f2f2f2;
  display: flex;
  flex-direction: row;
  width: 100%;
  align-items: center;
  justify-content: space-between;
}
</style>